package com.gomyb.admin.module.user.service.impl;

import com.gomyb.admin.module.user.dao.SysPermissionDao;
import com.gomyb.admin.module.user.model.SysPermission;
import com.gomyb.admin.module.user.model.pojo.TransferPermission;
import com.gomyb.admin.module.user.service.SysPermissionService;
import com.gomyb.common.base.BaseDao;
import com.gomyb.common.base.BaseServiceImpl;
import com.gomyb.result.JsonResult;
import com.gomyb.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:hellohesir@gmail.com">Mr_He</a>
 * 2019-04-01 16:57:21
 */
@Service
public class SysPermissionServiceImpl extends BaseServiceImpl<SysPermission, Long> implements SysPermissionService {

    @Override
    @Autowired
    public void setDao(BaseDao<SysPermission, Long> dao) {
        super.dao = dao;
    }

    @Override
    public List<SysPermission> findPermissionsByUserName(String userName) {
        String sql = "SELECT\n" +
                "\tt1.*\n" +
                "FROM\n" +
                "\tsys_permission t1\n" +
                "LEFT JOIN sys_role_permission t2 ON t1.id = t2.permission_id\n" +
                "LEFT JOIN sys_role t3 ON t3.id = t2.role_id\n" +
                "LEFT JOIN sys_user_role t4 ON t4.role_id = t3.id\n" +
                "LEFT JOIN sys_user t5 ON t5.id = t4.user_id\n" +
                "WHERE\n" +
                "\tt5.username = '" + userName + "'";
        return super.findBySql(sql, SysPermission.class);
    }

    @Override
    public void saveOrUpdate(List<SysPermission> sysPermissionList) {
        List<SysPermission> inDb = new ArrayList<>();
        for (SysPermission sysPermission : sysPermissionList) {
            SysPermission permission = ((SysPermissionDao) dao).getByPermissionUrl(sysPermission.getPermissionUrl());
            if (null == permission) {
                inDb.add(sysPermission);
            }
        }
        if (inDb.size() > 0) {
            super.saveAll(inDb);
        }
    }

    @Override
    public Result<TransferPermission> findTransferAll() {
        //language=SQL
        String sql = "SELECT\n" +
                "\t`permission_name` label,\n" +
                "\tid `key`\n" +
                "FROM\n" +
                "\tsys_permission\n" +
                "WHERE\n" +
                "\tpermission_name != ''\n" +
                "AND `status` = 1\n" +
                "AND is_default = 0";
        List<TransferPermission> transferPermissions = super.findBySql(sql, TransferPermission.class);
        return JsonResult.OK(transferPermissions);
    }

}
